package deviceinfo.wsm.com.deviceinfo.event;

import android.content.Context;
import android.content.SharedPreferences;

import com.google.gson.Gson;

import java.util.Set;
import java.util.TreeSet;

import deviceinfo.wsm.com.deviceinfo.WsmDeviceInfoSDK;
import deviceinfo.wsm.com.deviceinfo.upload.request.CusRequestEventBody;

/**
 * Created by 王家宝 on 2018/8/3.
 * TEL:18241150668
 * MAIL:639586819@qq.com
 */

public class EventSpy {

    private static final String EVENT_TYPE_DEFAULT = "点击";

    public static void onEvent(String eventName) {
        onEvent(eventName, EVENT_TYPE_DEFAULT);
    }

    public synchronized static void onEvent(String eventName, String eventType) {
        SharedPreferences sharedPreferences = WsmDeviceInfoSDK.getWsmSDK().
                getAppContext().getSharedPreferences(WsmDeviceInfoSDK.getWsmSDK().
                getAppContext().getPackageName() + "WsmTec", Context.MODE_PRIVATE);
        Set<String> eventList = sharedPreferences.getStringSet(WsmDeviceInfoSDK.EVENT_SP_KEY, null);
        if (eventList != null) {
            CusRequestEventBody.DataBean.UserActionBean bean = new CusRequestEventBody.DataBean.UserActionBean();
            bean.setActCount("0");
            bean.setActEvent(eventName);
            bean.setActEventType(eventType);
            bean.setTimestamp(System.currentTimeMillis());
            eventList.add(new Gson().toJson(bean));
            SharedPreferences.Editor editor = sharedPreferences.edit();
            editor.putStringSet(WsmDeviceInfoSDK.EVENT_SP_KEY, eventList);
            editor.apply();
        } else {
            SharedPreferences.Editor editor = sharedPreferences.edit();
            Set<String> tempList = new TreeSet<>();
            editor.putStringSet(WsmDeviceInfoSDK.EVENT_SP_KEY, tempList);
            editor.apply();
            onEvent(eventName, eventType);
        }

    }


}
